<template>
  <CustomerLayout>
    <div class="favorite-stores-container">
      <!-- 页面装饰背景 -->
      <div class="page-decoration">
        <div class="floating-shapes">
          <div class="shape shape-1"></div>
          <div class="shape shape-2"></div>
          <div class="shape shape-3"></div>
          <div class="shape shape-4"></div>
          <div class="shape shape-5"></div>
        </div>
      </div>

      <!-- 页面标题 -->
      <div class="page-header">
        <div class="title-wrapper">
          <div class="title-icon">⭐</div>
          <h1 class="main-title">我的收藏店铺</h1>
          <div class="title-decoration"></div>
        </div>
        <div class="subtitle">发现你喜爱的美食店铺</div>
        <div class="stats-bar">
          <div class="stat-item">
            <span class="stat-number">{{ stores.length }}</span>
            <span class="stat-label">家店铺</span>
          </div>
          <div class="stat-divider"></div>
          <div class="stat-item">
            <span class="stat-number">{{ currentPage }}</span>
            <span class="stat-label">/ {{ totalPages || 1 }} 页</span>
          </div>
        </div>
      </div>
      
      <div v-if="stores.length > 0" class="store-list">
        <div v-for="store in stores" :key="store.id" class="store-item">
          <div class="store-cover" @click="goToStore(store.id)">
            <el-image 
              :src="store.coverImage" 
              fit="cover"
              :lazy="true"
            >
              <template #error>
                <div class="image-placeholder">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <!-- 店铺状态遮罩 -->
            <div v-if="store.status !== 'OPEN'" class="store-status-overlay">
              <span class="status-text">{{ store.status === 'CLOSED' ? '休息中' : '暂停营业' }}</span>
            </div>
          </div>
          
          <div class="store-content" @click="goToStore(store.id)">
            <h3 class="store-name">{{ store.name }}</h3>
            
            <div class="store-info">
              <div class="rating">
                <el-rate 
                  v-model="store.rating" 
                  disabled 
                  size="small"
                />
                <span class="rating-score">{{ store.rating }}</span>
              </div>
              <div class="sales">月售 {{ store.monthSales }}+ 单</div>
            </div>
            
            <div class="store-tags" v-if="store.tags && store.tags.length > 0">
              <el-tag 
                v-for="(tag, index) in store.tags.slice(0, 3)" 
                :key="index"
                size="small"
                effect="plain"
              >
                {{ tag }}
              </el-tag>
            </div>
            
            <div class="store-delivery">
              <span class="time">{{ store.deliveryTime }}分钟</span>
              <span class="distance">{{ formatDistance(store.distance) }}</span>
            </div>
            
            <div v-if="store.promotion" class="store-promotion">
              <el-tag type="danger" size="small" effect="plain">
                {{ store.promotion }}
              </el-tag>
            </div>
          </div>
          
          <div class="store-actions">
            <el-button 
              type="danger" 
              circle 
              @click.stop="removeFavorite(store.id)"
              :loading="removingId === store.id"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="!loading" class="empty-state-wrapper">
        <div class="empty-decoration">
          <div class="empty-icon">🏪</div>
          <div class="empty-title">还没有收藏的店铺</div>
          <div class="empty-subtitle">快去发现你喜欢的美食店铺吧～</div>
          <div class="empty-actions">
            <el-button type="primary" size="large" @click="goToHome" class="explore-btn">
              <span>🔍</span>
              开始探索
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <!-- 分页 -->
      <div v-if="stores.length > 0 && totalPages > 1" class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          layout="prev, pager, next"
          :total="total"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </CustomerLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Delete, 
  Picture
} from '@element-plus/icons-vue';
import CustomerLayout from '@/components/customer/CustomerLayout.vue';
import { favoriteApi } from '@/api/customer';
import { Store } from '@/types/customer';

const router = useRouter();
const loading = ref(false);
const removingId = ref<number | null>(null);

// 店铺列表状态
const stores = ref<Store[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const totalPages = ref(0);

// 获取收藏的店铺列表
const fetchFavoriteStores = async (page = 1) => {
  try {
    loading.value = true;
    // 根据接口文档和微信小程序实现，使用正确的参数名
    const res = await favoriteApi.getFavoriteStores({ 
      page: page,
      size: pageSize.value 
    }) as any;
    
    console.log('收藏店铺响应:', res);
    console.log('收藏店铺响应类型:', typeof res);
    console.log('收藏店铺响应键:', Object.keys(res || {}));
    
    // 尝试多种可能的数据结构
    let storesData: any[] = [];
    
    // 检查各种可能的响应结构
    if (res) {
      // 情况1: 直接是数组
      if (Array.isArray(res)) {
        storesData = res;
        console.log('发现直接数组格式');
      }
      // 情况2: res.data 是数组
      else if (Array.isArray(res.data)) {
        storesData = res.data;
        console.log('发现 res.data 数组格式');
      }
      // 情况3: res.data.content 是数组（分页格式）
      else if (res.data && Array.isArray(res.data.content)) {
        storesData = res.data.content;
        console.log('发现 res.data.content 分页格式');
      }
      // 情况4: res.data.data 是数组（嵌套格式）
      else if (res.data && res.data.data && Array.isArray(res.data.data)) {
        storesData = res.data.data;
        console.log('发现 res.data.data 嵌套格式');
      }
      // 情况5: 其他可能的嵌套结构
      else if (res.data && res.data.data && res.data.data.content && Array.isArray(res.data.data.content)) {
        storesData = res.data.data.content;
        console.log('发现深度嵌套分页格式');
      }
      // 其他情况，尝试查找数组
      else {
        console.warn('未识别的响应格式，尝试查找数组字段:', res);
        
        // 递归查找数组字段
        const findArray = (obj: any): any[] => {
          if (Array.isArray(obj)) return obj;
          if (typeof obj === 'object' && obj !== null) {
            for (const key in obj) {
              if (Array.isArray(obj[key])) {
                console.log(`找到数组字段: ${key}`, obj[key]);
                return obj[key];
              } else if (typeof obj[key] === 'object') {
                const result = findArray(obj[key]);
                if (result.length > 0) return result;
              }
            }
          }
          return [];
        };
        
        storesData = findArray(res);
      }
    }
    
    console.log('最终解析的店铺数据:', storesData);
    console.log('店铺数据类型:', typeof storesData, 'isArray:', Array.isArray(storesData));
    
    // 确保 storesData 是数组
    if (!Array.isArray(storesData)) {
      console.warn('storesData 不是数组，设置为空数组');
      storesData = [];
    }
    
    // 获取分页信息
    const totalPagesFromAPI = res.data?.totalPages || 1;
    const totalElements = res.data?.totalElements || storesData.length;
    
    // 参考微信小程序，对店铺数据进行格式化处理
    stores.value = storesData.map((store: any) => ({
      ...store,
      // 确保必要字段存在
      id: store.id || store.storeId,
      storeId: store.storeId || store.id,
      name: store.name || '未知店铺',
      logo: store.logo || store.coverImage || '/images/store.png',
      coverImage: store.coverImage || store.logo || '/images/store.png',
      description: store.description || '',
      rating: store.rating || 0,
      monthSales: store.monthSales || 0,
      deliveryTime: store.deliveryTime || store.averageDeliveryTime || 30,
      deliveryFee: store.deliveryFee || 0,
      minOrderAmount: store.minOrderAmount || 0,
      status: store.status || 'OPEN',
      distance: store.distance || 0,
      tags: store.tags || [],
      promotion: store.promotion || ''
    }));
    
    // 更新分页信息
    total.value = totalElements;
    totalPages.value = totalPagesFromAPI;
    
  } catch (error) {
    console.error('获取收藏店铺失败:', error);
    ElMessage.error('获取收藏店铺列表失败');
    stores.value = [];
  } finally {
    loading.value = false;
  }
};

// 格式化距离 - 增强版本，与微信小程序保持一致
const formatDistance = (distance: number): string => {
  if (!distance || distance <= 0) {
    return '距离未知';
  }
  if (distance < 1) {
    return `${Math.round(distance * 1000)}m`;
  }
  return `${distance.toFixed(1)}km`;
};

// 前往店铺详情页 - 增加状态检查
const goToStore = (storeId: number) => {
  // 查找店铺信息以检查营业状态
  const store = stores.value.find(s => s.id === storeId);
  if (store && store.status && store.status !== 'OPEN') {
    ElMessage.warning('店铺未营业');
    return;
  }
  router.push(`/customer/store/${storeId}`);
};

// 前往首页
const goToHome = () => {
  router.push('/customer');
};

// 处理页面变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchFavoriteStores(page);
};

// 取消收藏
const removeFavorite = (storeId: number) => {
  ElMessageBox.confirm(
    '确定要取消收藏该店铺吗?',
    '取消收藏',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      removingId.value = storeId;
      // 调用取消收藏 API
      await favoriteApi.removeFavoriteStore(storeId);
      ElMessage.success('已取消收藏');
      
      // 参考微信小程序实现，取消收藏后重新加载数据
      // 这样可以确保分页信息的准确性
      await fetchFavoriteStores(1);
      currentPage.value = 1;
      
    } catch (error) {
      console.error('取消收藏失败:', error);
      ElMessage.error('取消收藏失败');
    } finally {
      removingId.value = null;
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 组件挂载时获取收藏店铺列表
onMounted(() => {
  fetchFavoriteStores();
});
</script>

<style scoped>
.favorite-stores-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  position: relative;
  min-height: 100vh;
}

/* 页面装饰背景 */
.page-decoration {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: -1;
  overflow: hidden;
}

.floating-shapes {
  position: relative;
  width: 100%;
  height: 100%;
}

.shape {
  position: absolute;
  border-radius: 50%;
  opacity: 0.1;
  animation: float 6s ease-in-out infinite;
}

.shape-1 {
  width: 120px;
  height: 120px;
  background: linear-gradient(45deg, #ff6b6b, #ee5a24);
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.shape-2 {
  width: 80px;
  height: 80px;
  background: linear-gradient(45deg, #4ecdc4, #00b894);
  top: 20%;
  right: 15%;
  animation-delay: 2s;
}

.shape-3 {
  width: 100px;
  height: 100px;
  background: linear-gradient(45deg, #45b7d1, #74b9ff);
  bottom: 30%;
  left: 5%;
  animation-delay: 4s;
}

.shape-4 {
  width: 60px;
  height: 60px;
  background: linear-gradient(45deg, #96ceb4, #00cec9);
  bottom: 15%;
  right: 20%;
  animation-delay: 1s;
}

.shape-5 {
  width: 90px;
  height: 90px;
  background: linear-gradient(45deg, #ffeaa7, #fdcb6e);
  top: 50%;
  right: 5%;
  animation-delay: 3s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

/* 页面标题区域 */
.page-header {
  margin-bottom: 24px;
  text-align: center;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(248, 249, 250, 0.9));
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 20px 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.title-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 8px;
  position: relative;
}

.title-icon {
  font-size: 32px;
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

.main-title {
  font-size: 28px;
  font-weight: 800;
  margin: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
}

.title-decoration {
  width: 3px;
  height: 40px;
  background: linear-gradient(to bottom, #667eea, #764ba2);
  border-radius: 2px;
  animation: slideUp 1s ease-out;
}

@keyframes slideUp {
  from {
    height: 0;
  }
  to {
    height: 40px;
  }
}

.subtitle {
  font-size: 16px;
  color: #666;
  margin-bottom: 16px;
  font-weight: 500;
  opacity: 0.8;
}

.stats-bar {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 12px;
  padding: 10px 20px;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.stat-number {
  font-size: 20px;
  font-weight: 700;
  color: #2c3e50;
}

.stat-label {
  font-size: 13px;
  color: #7f8c8d;
  font-weight: 500;
}

.stat-divider {
  width: 1px;
  height: 24px;
  background: linear-gradient(to bottom, transparent, #ddd, transparent);
}

.store-list {
  margin-bottom: 20px;
}

.store-item {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
  /* 添加彩色边框装饰 */
  border-left: 4px solid transparent;
  background-image: linear-gradient(white, white), 
                   linear-gradient(45deg, #ff6b6b, #4ecdc4, #45b7d1, #96ceb4, #ffeaa7);
  background-origin: border-box;
  background-clip: padding-box, border-box;
  transition: all 0.3s ease;
}

.store-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  border-left-width: 6px;
}

.store-item:nth-child(5n+1) {
  background-image: linear-gradient(white, white), 
                   linear-gradient(45deg, #ff6b6b, #ee5a24);
}

.store-item:nth-child(5n+2) {
  background-image: linear-gradient(white, white), 
                   linear-gradient(45deg, #4ecdc4, #00b894);
}

.store-item:nth-child(5n+3) {
  background-image: linear-gradient(white, white), 
                   linear-gradient(45deg, #45b7d1, #74b9ff);
}

.store-item:nth-child(5n+4) {
  background-image: linear-gradient(white, white), 
                   linear-gradient(45deg, #96ceb4, #00cec9);
}

.store-item:nth-child(5n+5) {
  background-image: linear-gradient(white, white), 
                   linear-gradient(45deg, #ffeaa7, #fdcb6e);
}

.store-cover {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
  cursor: pointer;
  position: relative;
}

.store-cover .el-image {
  width: 100%;
  height: 100%;
}

.store-status-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
}

.status-text {
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.store-content {
  flex: 1;
  cursor: pointer;
}

.store-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  line-clamp: 1;
  overflow: hidden;
}

.store-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.rating {
  margin-right: 15px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.rating-score {
  font-size: 14px;
  color: #f39c12;
  font-weight: 600;
}

.sales {
  font-size: 12px;
  color: #999;
}

.store-tags {
  margin-bottom: 8px;
}

.store-tags .el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.store-delivery {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.store-delivery .time {
  margin-right: 15px;
}

.store-promotion {
  margin-top: 5px;
}

.store-actions {
  display: flex;
  align-items: center;
}

.loading-container {
  padding: 20px;
}

/* 空状态样式 */
.empty-state-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  padding: 60px 20px;
}

.empty-decoration {
  text-align: center;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(248, 249, 250, 0.9));
  backdrop-filter: blur(10px);
  border-radius: 30px;
  padding: 60px 40px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  max-width: 500px;
  width: 100%;
}

.empty-icon {
  font-size: 120px;
  margin-bottom: 30px;
  animation: bounce 2s ease-in-out infinite;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-20px);
  }
  60% {
    transform: translateY(-10px);
  }
}

.empty-title {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.empty-subtitle {
  font-size: 18px;
  color: #7f8c8d;
  margin-bottom: 40px;
  line-height: 1.6;
}

.empty-actions {
  margin-top: 30px;
}

.explore-btn {
  font-size: 18px;
  padding: 15px 30px;
  border-radius: 25px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.explore-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 35px rgba(102, 126, 234, 0.4);
}

.explore-btn span {
  margin-right: 8px;
  font-size: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 576px) {
  .store-item {
    flex-direction: column;
  }
  
  .store-cover {
    width: 100%;
    height: 150px;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .store-actions {
    position: absolute;
    top: 15px;
    right: 15px;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 50%;
  }
}
</style>
